// API服务模块 - 模拟后端接口
const API_BASE_URL = 'http://localhost:8080/api'

// 模拟延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 通用请求函数
async function request(endpoint, options = {}) {
  const url = `${API_BASE_URL}${endpoint}`
  const config = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  if (config.body && typeof config.body === 'object') {
    config.body = JSON.stringify(config.body)
  }

  try {
    await delay(500) // 模拟网络延迟
    const response = await fetch(url, config)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await response.json()
  } catch (error) {
    console.error('API request failed:', error)
    throw error
  }
}

// 网关配置API
export const gatewayApi = {
  // 获取所有网关配置
  async getGateways() {
    // 模拟数据
    return [
      {
        id: 1,
        name: '主网关服务',
        port: 8080,
        host: 'localhost',
        isActive: true,
        createdAt: '2024-01-15'
      },
      {
        id: 2,
        name: '测试网关',
        port: 8081,
        host: 'localhost',
        isActive: false,
        createdAt: '2024-01-20'
      }
    ]
  },

  // 创建网关配置
  async createGateway(data) {
    console.log('Creating gateway:', data)
    return { ...data, id: Date.now(), createdAt: new Date().toISOString().split('T')[0] }
  },

  // 更新网关配置
  async updateGateway(id, data) {
    console.log('Updating gateway:', id, data)
    return { ...data, id }
  },

  // 删除网关配置
  async deleteGateway(id) {
    console.log('Deleting gateway:', id)
    return { success: true }
  },

  // 切换网关状态
  async toggleGateway(id, isActive) {
    console.log('Toggling gateway status:', id, isActive)
    return { success: true }
  }
}

// 路由管理API
export const routeApi = {
  // 获取所有路由规则
  async getRoutes() {
    return [
      {
        id: 1,
        path: '/api/users',
        target: 'http://localhost:3001/api/users',
        method: 'GET',
        isActive: true,
        gatewayId: 1,
        createdAt: '2024-01-15'
      },
      {
        id: 2,
        path: '/api/auth/*',
        target: 'http://localhost:3002/api/auth',
        method: 'ANY',
        isActive: true,
        gatewayId: 1,
        createdAt: '2024-01-16'
      },
      {
        id: 3,
        path: '/api/products',
        target: 'http://localhost:3003/api/products',
        method: 'GET',
        isActive: false,
        gatewayId: 2,
        createdAt: '2024-01-18'
      }
    ]
  },

  // 创建路由规则
  async createRoute(data) {
    console.log('Creating route:', data)
    return { ...data, id: Date.now(), createdAt: new Date().toISOString().split('T')[0] }
  },

  // 更新路由规则
  async updateRoute(id, data) {
    console.log('Updating route:', id, data)
    return { ...data, id }
  },

  // 删除路由规则
  async deleteRoute(id) {
    console.log('Deleting route:', id)
    return { success: true }
  },

  // 切换路由状态
  async toggleRoute(id, isActive) {
    console.log('Toggling route status:', id, isActive)
    return { success: true }
  }
}

// 用户管理API
export const userApi = {
  // 获取所有用户
  async getUsers() {
    return [
      {
        id: 1,
        username: 'admin',
        email: 'admin@gateway.com',
        role: 'admin',
        isActive: true,
        createdAt: '2024-01-10',
        lastLogin: '2024-01-26'
      },
      {
        id: 2,
        username: 'developer',
        email: 'dev@gateway.com',
        role: 'developer',
        isActive: true,
        createdAt: '2024-01-15',
        lastLogin: '2024-01-25'
      },
      {
        id: 3,
        username: 'viewer',
        email: 'viewer@gateway.com',
        role: 'user',
        isActive: false,
        createdAt: '2024-01-20',
        lastLogin: '2024-01-22'
      }
    ]
  },

  // 创建用户
  async createUser(data) {
    console.log('Creating user:', data)
    return { 
      ...data, 
      id: Date.now(), 
      createdAt: new Date().toISOString().split('T')[0],
      lastLogin: '-'
    }
  },

  // 更新用户
  async updateUser(id, data) {
    console.log('Updating user:', id, data)
    return { ...data, id }
  },

  // 删除用户
  async deleteUser(id) {
    console.log('Deleting user:', id)
    return { success: true }
  },

  // 切换用户状态
  async toggleUser(id, isActive) {
    console.log('Toggling user status:', id, isActive)
    return { success: true }
  }
}

// 菜单管理API
export const menuApi = {
  // 获取所有菜单
  async getMenus() {
    return [
      {
        id: 1,
        name: '仪表板',
        path: '/dashboard',
        icon: 'dashboard',
        parentId: null,
        order: 1,
        isActive: true,
        permissions: ['admin', 'developer', 'user'],
        createdAt: '2024-01-10'
      },
      {
        id: 2,
        name: '网关管理',
        path: '/gateway',
        icon: 'gateway',
        parentId: null,
        order: 2,
        isActive: true,
        permissions: ['admin', 'developer'],
        createdAt: '2024-01-10'
      },
      {
        id: 3,
        name: '路由管理',
        path: '/routes',
        icon: 'route',
        parentId: 2,
        order: 1,
        isActive: true,
        permissions: ['admin', 'developer'],
        createdAt: '2024-01-10'
      },
      {
        id: 4,
        name: '用户管理',
        path: '/users',
        icon: 'users',
        parentId: null,
        order: 3,
        isActive: true,
        permissions: ['admin'],
        createdAt: '2024-01-10'
      },
      {
        id: 5,
        name: '系统设置',
        path: '/settings',
        icon: 'settings',
        parentId: null,
        order: 4,
        isActive: true,
        permissions: ['admin'],
        createdAt: '2024-01-10'
      }
    ]
  },

  // 创建菜单
  async createMenu(data) {
    console.log('Creating menu:', data)
    return { 
      ...data, 
      id: Date.now(), 
      createdAt: new Date().toISOString().split('T')[0]
    }
  },

  // 更新菜单
  async updateMenu(id, data) {
    console.log('Updating menu:', id, data)
    return { ...data, id }
  },

  // 删除菜单
  async deleteMenu(id) {
    console.log('Deleting menu:', id)
    return { success: true }
  },

  // 切换菜单状态
  async toggleMenu(id, isActive) {
    console.log('Toggling menu status:', id, isActive)
    return { success: true }
  },

  // 获取菜单树
  async getMenuTree() {
    const menus = await this.getMenus()
    return this.buildMenuTree(menus)
  },

  // 构建菜单树
  buildMenuTree(menus) {
    const menuMap = new Map()
    const rootMenus = []
    
    // 创建菜单映射
    menus.forEach(menu => {
      menuMap.set(menu.id, { ...menu, children: [] })
    })
    
    // 构建树结构
    menus.forEach(menu => {
      if (menu.parentId) {
        const parent = menuMap.get(menu.parentId)
        if (parent) {
          parent.children.push(menuMap.get(menu.id))
          parent.children.sort((a, b) => a.order - b.order)
        }
      } else {
        rootMenus.push(menuMap.get(menu.id))
      }
    })
    
    return rootMenus.sort((a, b) => a.order - b.order)
  }
}

// 系统统计API
export const statsApi = {
  // 获取系统统计信息
  async getStats() {
    return {
      gatewayCount: 3,
      userCount: 15,
      routeCount: 8,
      activeConnections: 42,
      systemStatus: {
        api: 'running',
        database: 'normal',
        load: 'medium'
      }
    }
  }
}

export default {
  gatewayApi,
  routeApi,
  userApi,
  statsApi,
  menuApi
}